package com.usian.wemedia.filter;

import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(2)
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.获取httpservletRequest和httpservletResponse
        HttpServletRequest servletRequest=(HttpServletRequest)request;
        HttpServletResponse servletResponse=(HttpServletResponse)response;
        //2.获取请求头中的userid
        String userId = servletRequest.getHeader("userId");
        if(userId!=null){
            WmUser wmUser = new WmUser();
            wmUser.setApUserId(Integer.parseInt(userId));
            //保存在ThreadLocal中d
            WmThreadLocalUtils.setUser(wmUser);
        }
        chain.doFilter(servletRequest, servletResponse);
    }
}
